package com.qt.judge;

import com.alibaba.fastjson.JSON;
import com.qt.common.LanguageScriptEnum;
import com.qt.pojo.dto.SingleJudgeResultDTO;
import com.qt.utils.DataTransform;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author pgw
 * @version 1.0
 * @description
 * @date Create by 2023/10/2 13:10
 */
@Slf4j
public class JudgeRun {


    public  static SingleJudgeResultDTO run(String stdInPath){
        String  judgeCoreScript = JudgeHolder.getJudgeCoreScriptPath();
        String workingPath = JudgeHolder.getJudgeWorkingPath();
        String name = "Main";
       log.debug("judgeCoreScript:{}",judgeCoreScript);
        LanguageScriptEnum language = LanguageScriptEnum.toLanguageType(JudgeHolder.getJudgeConfiguration().getLanguage());

        boolean isCppFamily = (language == LanguageScriptEnum.C || language == LanguageScriptEnum.C_PLUS_PLUS);
        String[] command = {
                judgeCoreScript,
                "-r", JudgeHolder.getRunnerScriptPath(),
                "-o", workingPath + "/" + name + ".out",
                "-t", String.valueOf(2000),
                "-c", String.valueOf(4000),
                "-m", String.valueOf(1024*1024),
                "-f", String.valueOf(20000),
                "-e", workingPath + "/" + name + ".err",
                "-i", stdInPath,
                "-g",String.valueOf(isCppFamily ? 1 : 0)
        };
        List<String> result;
        try {
            Runtime runner = JudgeHolder.getRunner();
            Process process = runner.exec(command);
            process.waitFor();
            result = readStdout(process);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        log.debug("运行结果为:{}" , result);

        // 将判题核心的stdout转换成数据传输对象
        return JSON.parseObject(DataTransform.stringListToString(result), SingleJudgeResultDTO.class);

    }

    /**
     * 获取运行的脚本/可执行文件的输出
     *
     * @param process 运行的进程对象
     * @return String 进程输出
     * @throws IOException an I/O exception
     * @author pgw
     */
    private static List<String> readStdout(Process process) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        List<String> stringList = new ArrayList<>();
        String temp;
        while ((temp = reader.readLine()) != null) {
            stringList.add(temp);
        }
        BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        while ((temp = errReader.readLine()) != null) {
            stringList.add(temp);
        }
        return stringList;
    }
}
// /home/judge/y_judge  -r ./run  -o ./Main.out -t 2000 -c 4000 -m 1000000000 -f 200000 -e Main.errr -i ./Main.in -g 1
